from django.views.decorators.csrf import csrf_exempt
from dj3.utils.response import  SuccessJsonResponse ,ErrorJsonResponse
from dj3.utils import tokenUtil,jsonUtil
from dj3.modules.sys.user.models.Models import AdminInfo


@csrf_exempt
def login(request):
    if request.method == 'POST':
        dic=jsonUtil.strToJson(request.body)
        username=dic["username"]
        password=dic["password"]
        try:
            obj = AdminInfo.objects.get(username=username,password=password)
            dic = {}
            dic['token']=tokenUtil.create_token(obj.id)
            return SuccessJsonResponse(dic)
        except Exception as e:
            print(e)
        return ErrorJsonResponse(None, "访问失败")

    else:
        return ErrorJsonResponse(None, "访问失败")


@csrf_exempt
def info(request):
    if request.method == 'GET':
        try:
            token = request.META.get("HTTP_X_TOKEN")
            id=tokenUtil.get_username(token)
            obj=AdminInfo.objects.get(id=id)
            dic = {}
            dic["roles"] = obj.role_ids
            dic["name"] = obj.username
            dic["avatar"] = obj.avatar
            return SuccessJsonResponse(dic)
        except:
            return ErrorJsonResponse(None, "访问失败")
    else:
        return ErrorJsonResponse(None, "访问失败")


@csrf_exempt
def add(request):
    if request.method == 'POST':
        try:
            dic = jsonUtil.strToJson(request.body)
            username = dic["username"]
            password = dic["password"]

            admininfo=AdminInfo.objects.filter(username=username)
            if admininfo.exists():
                return ErrorJsonResponse(None, "用户已存在")
            print()
            dic = {'username':username, 'password': password }
            AdminInfo.objects.create(**dic)
            return SuccessJsonResponse(dic)
        except Exception as e:
            print(e)
            return ErrorJsonResponse(None, "访问失败")
    else:
        return ErrorJsonResponse(None, "访问失败")



@csrf_exempt
def modipassword(request):
    if request.method == 'POST':
        try:
            dic = jsonUtil.strToJson(request.body)
            username = dic["username"]
            password = dic["password"]
            oldpassword = dic["oldpassword"]


            admininfo=AdminInfo.objects.filter(username=username,password=passwordold)
            if admininfo.exists():
                AdminInfo.objects.filter(username=username, password=passwordold).update(password=password)
                return SuccessJsonResponse("修改成功")
            else:
                return ErrorJsonResponse("账户不存在或者旧密码不正确")
        except Exception as e:
            print(e)
            return ErrorJsonResponse(None, "访问失败")
    else:
        return ErrorJsonResponse(None, "访问失败")